package org.extplus.test.ajax;

import java.util.List;

import org.extplus.ajax.AbstractAjaxTask;
import org.extplus.base.Response;
import org.extplus.test.shared.SampleData;
import org.extplus.test.shared.SampleData.Company;

import com.google.gson.Gson;

public class AjaxTaskExampleImpl extends AbstractAjaxTask<String> {
    private static Gson gson = new Gson();

    private static int requestCount = 0;

    private static SampleData data;

    private boolean tag;

    public AjaxTaskExampleImpl() {
        if (data == null) {
            data = new SampleData();
        }
    }

    public String parseParams(String uri, String params) {
        return params;
    }

    public Response<String> processRequest(String uri, String params) {
        Response<String> resp = new Response<String>();
        if (!tag) {
            requestCount++;
            tag = true;
        }

        if (uri.equalsIgnoreCase("loadstore")) {
            resp.setData(gson.toJson(getCompanys(), Company[].class));
        } else {
            resp.setData(uri + " - 请求次数: " + requestCount);
        }

        resp.setSuccess(true);
        resp.setMessage("success");
        return resp;
    }

    public Company[] getCompanys() {
        int s = data.companys.size() - 3 - requestCount;
        s = (s < 0) ? 0 : s;
        List<Company> comps = data.companys.subList(s, data.companys.size());
        return comps.toArray(new Company[comps.size()]);
    }
}
